<template>
    <div class="step_container">
        <el-steps :active="activeStep" align-center class="apply_step">
            <el-step title="第一步" description="填写信息" />
            <el-step title="第二步" description="提交申请" />
            <el-step title="第三步" description="审批通过" />
        </el-steps>
        <el-form ref="applyFormRef" 
            label-width="120px" 
            :rules="rules"
            :model="applyInfo" 
            class="apply_form"
            :disabled="disableForm"
            status-icon>
            <el-form-item label="申请账号" prop="account">
                <el-input type="text" v-model="applyInfo.account" disabled/>
            </el-form-item>
            <el-form-item label="申请类型" prop="applyType">
                <el-input type="text" v-model="operationType" disabled />
            </el-form-item>

            <el-tooltip
                effect="dark"
                content="请输入要申请的容量大小(1-10240), 单位MB"
                placement="top-start">
                <el-form-item label="申请容量" prop="applyVolume">
                    <el-input type="number"
                        v-model="applyInfo.applyVolume" 
                        placeholder="请输入要申请的容量大小(1-10240), 单位MB"
                        @input="clampApplyVolume">
                        <template #suffix>
                            <span>MB</span>
                        </template>
                    </el-input>
                </el-form-item>
            </el-tooltip>
 
            <el-form-item label="申请用途" prop="applyReason">
                <el-input 
                    autosize 
                    type="textarea" 
                    v-model="applyInfo.applyReason" 
                    placeholder="请说明申请的用途" 
                    maxlength="100"
                    show-word-limit />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitApplyForm(applyFormRef)">申请</el-button>
                <el-button @click="resetApplyForm(applyFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>


<script setup lang='ts' name='Applying'>
    import { ref, reactive, onMounted, computed } from "vue";
    import { ApplyInfo } from "@/types/type";
    import type { FormInstance, FormRules } from 'element-plus'
    import { useUserInfoStore } from "@/store/userInfo";
    import { useSettingInfoStore } from "@/store/settingInfo";
    import request from "@/requests/request";

    const userInfo = useUserInfoStore()
    const settingInfo = useSettingInfoStore()
    const applyFormRef = ref<FormInstance>()
    let disableForm = ref(false)
    let activeStep = ref(1)
    let applyInfo = reactive<ApplyInfo>({
        account: userInfo.account,
        applyType: 1,
        applyVolume: 1,
        applyReason: "",
    })

    let operationType = computed(() => {
        return applyInfo.applyType === 1 ? "新建容量" : "扩展容量"
    })

    const rules = reactive<FormRules<ApplyInfo>>({
        account: [
            {
                required: true,
                min: 3,
                max: 18,
                message: '请输入登录的账号, 长度限于3到18位',
                trigger: 'blur'
            },
        ],
        applyType: [
            {
                required: true,
                message: '请选择操作类型',
                trigger: 'blur',
            },
        ],
        applyVolume: [
            {
                required: true,
                message: '请输入要申请的容量大小, 单位MB',
                trigger: 'blur',
            },
        ],
        applyReason: [
            {
                required: true,
                min: 2,
                max: 100,
                message: '请输入申请的原因, 长度限于2到100位',
                trigger: 'blur',
            },
        ],
    })

    const submitApplyForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) {
            return
        }
        await formEl.validate((valid, fields) => {
            if (valid) {
                settingInfo.isRefreshing = true
                const data = {
                    "applyType": `${applyInfo.applyType}`,
                    "applyVolume": `${applyInfo.applyVolume}`,
                    "applyReason": applyInfo.applyReason,
                }
                request.post("/submitApply", data).then((res: any) => {
                    settingInfo.isRefreshing = false
                    const { data, message, resCode } = res.data
                    console.log("/submitApply", data, message, resCode)
                    if (data) {
                        activeStep.value = 2
                    }
                }).catch((reason: any) => {
                    settingInfo.isRefreshing = false
                    console.log(reason)
                })
            } else {
                console.log('error submit!', fields)
            }
        })
    }

    const resetApplyForm = (formEl: FormInstance | undefined) => {
        if (!formEl) {
            return
        }
        formEl.resetFields()
    }

    onMounted(() => {
        const spaceStatusQuery = request.post("/querySpaceStatus")
        const applyRecordQuery = request.post("/queryApplyRecord")

        /**
         * 1、既没有审批通过的记录，也没有正在等待审批的记录  ---可以发起新建申请
         * 2、没有审批通过的记录，有正在等待审批的记录  ---不能发起任何申请
         * 3、有审批通过的记录，没有正在等待审批的记录  ---可以发起扩容申请
         * 4、有审批通过的记录，也有正在等待审批的记录  ---不能发起任何申请
         */
        Promise.all([spaceStatusQuery, applyRecordQuery]).then(resultArr => {
            console.log("/querySpaceStatus && /queryApplyRecord", resultArr)
            const data1 = resultArr[0].data.data
            const resCode1 = resultArr[0].data.resCode
            const data2 = JSON.parse(resultArr[1].data.data).filter((item: any) => {
                return item.applyStatus === 1  // 提交申请，等待审批的记录
            })
            const resCode2 = resultArr[1].data.resCode
            if (data1 === null && resCode1 === 0 && data2.length === 0 && resCode2 === 0) {
                console.log("既没有审批通过的记录，也没有正在等待审批的记录")
                disableForm.value = false
                activeStep.value = 1
                applyInfo.account = userInfo.account
                applyInfo.applyType = 1
                applyInfo.applyVolume = 1
                applyInfo.applyReason = ""
            } else if (data1 === null && resCode1 === 0 && data2.length === 1 && resCode2 === 0) {
                console.log("没有审批通过的记录，有正在等待审批的记录")
                disableForm.value = true
                activeStep.value = 2
                applyInfo.account = userInfo.account
                applyInfo.applyType = 1
                applyInfo.applyVolume = data2[0].applyVolume
                applyInfo.applyReason = data2[0].applyReason
            } else if (data1 !== null && resCode1 === 0 && data2.length === 0 && resCode2 === 0) {
                console.log("有审批通过的记录，没有正在等待审批的记录")
                disableForm.value = false
                activeStep.value = 1
                applyInfo.account = userInfo.account
                applyInfo.applyType = 2
                applyInfo.applyVolume = 1
                applyInfo.applyReason = ""
            } else if (data1 !== null && resCode1 === 0 && data2.length === 1 && resCode2 === 0) {
                console.log("有审批通过的记录，也有正在等待审批的记录")
                disableForm.value = true
                activeStep.value = 2
                applyInfo.account = userInfo.account
                applyInfo.applyType = 2
                applyInfo.applyVolume = data2[0].applyVolume
                applyInfo.applyReason = data2[0].applyReason
            } else {
                console.log("没有考虑到的异常情况")
            }
        }).catch((reason: any) => {
            console.log("/querySpaceStatus && /queryApplyRecord", reason)
        })
    })


    function clampApplyVolume() {
        if(applyInfo.applyVolume > 10240) {
            applyInfo.applyVolume = 10240
        } else if (applyInfo.applyVolume <= 0) {
            applyInfo.applyVolume = 1
        }
    }

</script>

<style scoped lang='scss'>
    .step_container {
        display: flex;
        flex-direction: column;
        --el-color-primary: purple;

        .apply_step {
            margin-top: 20px;
        }

        .apply_form {
            margin-top: 40px;
            width: 60%;
            align-self: center;
        }
    }
</style>